<!DOCTYPE HTML>
<html>
<head>
    <title>My WebSocket</title>
</head>

<body>
Welcome<br/>
<input id="text" type="text" /><button onclick="send()">Send</button>    <button onclick="closeWebSocket()">Close</button>
<div id="message">
</div>
</body>

<script type="text/javascript">
    var websocket = null;

    //鍒ゆ柇褰撳墠娴忚鍣ㄦ槸鍚︽敮鎸乄ebSocket
    if('WebSocket' in window){
        websocket = new WebSocket("ws://192.168.0.139:8090/websocket");
    }
    else{
        alert('Not support websocket')
    }

    //杩炴帴鍙戠敓閿欒鐨勫洖璋冩柟娉�
    websocket.onerror = function(){
        setMessageInnerHTML("error");
    };

    //杩炴帴鎴愬姛寤虹珛鐨勫洖璋冩柟娉�
    websocket.onopen = function(event){
        setMessageInnerHTML("open");
    }

    //收到状态
    websocket.onmessage = function(event){
        setMessageInnerHTML(event.data);
    }

    //杩炴帴鍏抽棴鐨勫洖璋冩柟娉�
    websocket.onclose = function(){
        setMessageInnerHTML("close");
    }

    //鐩戝惉绐楀彛鍏抽棴浜嬩欢锛屽綋绐楀彛鍏抽棴鏃讹紝涓诲姩鍘诲叧闂瓀ebsocket杩炴帴锛岄槻姝㈣繛鎺ヨ繕娌℃柇寮�灏卞叧闂獥鍙ｏ紝server绔細鎶涘紓甯搞��
    window.onbeforeunload = function(){
        websocket.close();
    }

    //灏嗘秷鎭樉绀哄湪缃戦〉涓�
    function setMessageInnerHTML(innerHTML){
        document.getElementById('message').innerHTML += innerHTML + '<br/>';
    }

    //鍏抽棴杩炴帴
    function closeWebSocket(){
        websocket.close();
    }

    //鍙戦�佹秷鎭�
    function send(){
        var message = document.getElementById('text').value;
        websocket.send(message);
    }
</script>
</html>